import { Module } from 'vuex'
import _ from 'lodash'
import historyReadStateTypes from './types'
import RootStateTypes from '../../types'
import { HistoryItem } from '@/common/types'
import { setStore, getStore } from '@/utils/store'

const historyReadModule: Module<historyReadStateTypes, RootStateTypes> = {
  namespaced: true,
  state: {
    historyReadList:
      getStore({
        name: 'historyReadList'
      }) || []
  },
  mutations: {
    SET_HISTORY_LIST(state: historyReadStateTypes, historyReadList: HistoryItem[]) {
      state.historyReadList = historyReadList
      setStore({
        name: 'historyReadList',
        content: historyReadList
      })
    }
  },
  actions: {
    addHistoryRead({ state, commit }, historyItem: HistoryItem) {
      return new Promise((resolve, reject) => {
        try {
          let historyList: HistoryItem[] = _.cloneDeep(state.historyReadList)
          const index = historyList.findIndex((item) => {
            return item.book_id === historyItem.book_id
          })
          if (index !== -1) {
            historyList.splice(index, 1)
          }
          historyList.push(historyItem)
          historyList = _.orderBy(historyList, ['read_time'], ['desc'])
          commit('SET_HISTORY_LIST', historyList)
          resolve('ok')
        } catch (error) {
          reject(error)
        }
      })
    },
    delHistoryRead({ state, commit }, historyItem: HistoryItem) {
      return new Promise((resolve, reject) => {
        try {
          let historyList: HistoryItem[] = _.deepClone(state.historyReadList)
          historyList = historyList.filter((item) => {
            return item.book_id !== historyItem.book_id
          })
          historyList = _.orderBy(historyList, ['read_time'], ['desc'])
          commit('SET_HISTORY_LIST', historyList)
          resolve('ok')
        } catch (error) {
          reject(error)
        }
      })
    },
    clearHistoryList({ commit }) {
      commit('SET_HISTORY_LIST', [])
    }
  }
}

export default historyReadModule
